//
//  SLNetworkTool.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/21.
//  Copyright © 2016年 大天朝. All rights reserved.
//

import UIKit
import AFNetworking

//MARK: - 统一管理错误信息
enum SLNetworkToolError: Int {
    var netDoamin: String {
        get {
            return "cn.itcast.error.net"
        }
    }
    var dbDomain: String {
        get {
            return "cn.itcast.error.db"
        }
    }
    case RepeatRefresh = -1
    case EmptyAccessToken = -2
    
    //枚举里面可以有属性
    var errorDescription: String {
        get {
            switch self {
                case RepeatRefresh: return "嘿!哥们!手速不要这么快..."
                case EmptyAccessToken: return "access_token 没有值"
            }
        }
    }
    //枚举里面可以写方法
    func error() -> NSError {
        return NSError(domain: netDoamin, code: self.rawValue, userInfo: ["errorDescripion" : self.errorDescription])
    }
}

class SLNetworkTool: NSObject {
    //单例
    static let sharedInstance: SLNetworkTool = SLNetworkTool()
    
    //私有化构造函数
    private override init() {
        super.init()
        //failed: unacceptable content-type: text/plain"
        //设置AFN支持 text/plain类型
        AFNManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }
    
    //MARK: - Oauth授权
//    private let client_id = "1763587078"
//    private let client_secret = "4cb1e94b602fbc322a0e9590a57b882d"
//    let redierct_url = "http://www.weibo.com"
    //修改了应用
    private let client_id = "2553063838"
    private let client_secret = "489b13ee03fd1df1ed01efb321ad56c5"
    let redierct_url = "http://www.baidu.com"
    let grant_type = "authorization_code"
    

//    App Key：2553063838
//    App Secret：489b13ee03fd1df1ed01efb321ad56c5
//    授权回调页：http://www.baidu.com
    ///>授权的URL
    func oAuthURL() -> NSURL {
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redierct_url)")!
    }
    
    //AFN
    let AFNManager: AFHTTPSessionManager = AFHTTPSessionManager(baseURL: SLBaseURL)
    
    //自己来封装GET
    func requestGET(URLString: String, var parameters: [String: AnyObject]?, requestCallback: (result: [String: AnyObject]?, error: NSError?) -> ()) {
       
        //自己来拼接assessToken.外面不用传入
        guard let access_token = SLUserAccountViewModel.sharedInstance.userAccount?.access_token else {
//            SLPrint(msg: "access_token 没有值")
            //告诉调用的人出错了.没有access_token
//            let emptyAcc = SLNetworkToolError.EmptyAccessToken
//            let error = NSError(domain: "cn.itaca.error.net", code: emptyAcc.rawValue , userInfo: ["errorDescripion" : emptyAcc.errorDescription])
//            requestCallback(result: nil, error: error)
            requestCallback(result: nil, error: SLNetworkToolError.EmptyAccessToken.error())
            return
        }
        //如果没有传入参数.创建参数字典
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"] = access_token
        
           AFNManager.GET(URLString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            SLPrint(msg: "GET请求成功: \(result)")
            let dict = result as? [String: AnyObject]
            requestCallback(result: dict, error: nil)
            
            }, failure: { (_, error) -> Void in
                SLPrint(msg: "GET请求失败: \(error)")
                 requestCallback(result: nil, error: error)
           })
     }
    
    //自己来封装POST
    func requestPOST(URLString: String, parameters: AnyObject?, requestCallback: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        AFNManager.POST(URLString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            SLPrint(msg: "POST请求成功: \(result)")
            //网络请求回来是POST
                let dict = result as? [String: AnyObject]
                requestCallback(result: dict, error: nil)
            }) { (_, error) -> Void in
                SLPrint(msg: "POST请求失败: \(error)")
                requestCallback(result: nil, error: error)
        }
    }

}


/*
//授权连接
https://api.weibo.com/oauth2/authorize?client_id=1763587078&redirect_uri=http://www.weibo.com

*/
//我的信息
//https://api.weibo.com/2/users/show.json?access_token=2.00Y6ZEZFsYp2vB874724f88c8i3OIC&uid=5098925356